﻿using LocalTest.Application.Contracts.Shared;
using LocalTest.Domain.Entities;
using LocalTest.Infrastructure.Context;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace LocalTest.Web.Controllers;

[ApiController]
[Route("[controller]")]
[Authorize]
public class UserLayerController : ControllerBase
{
    [HttpGet("getAFields")]
    public IActionResult GetAFields()
    {
        return new JsonResult(new ResponseResult()
        {
            Data = new SearchFields()
            {
                GetKeyWords =
                [
                    new SearchFields.KeyWordItem("name", "名称"),
                    new SearchFields.KeyWordItem("status", "状态")
                ]
            }
        });
    }

    [HttpGet("")]
    public IActionResult SelectList()
    {
        using AppDbContext context = new();
        var list = context.UserLayers.ToList();
        var result = new ResponseResult() { Data = new ListData() { Data = list, Total = list.Count } };
        Console.WriteLine(JsonConvert.SerializeObject(result));
        return new JsonResult(result);
    }

    [HttpGet("{id}")]
    public IActionResult SelectById(int id)
    {
        AppDbContext context = new();
        var entity = context.UserLayers.FirstOrDefault(u => u.Id == id.ToString());
        if (entity == null)
        {
            return new JsonResult(new ResponseResult(ResponseType.Error) { Status = "error", Msg = "数据不存在" });
        }

        return new JsonResult(
            new ResponseResult() { Data = entity });
    }

    [HttpPost("")]
    public IActionResult InsertData([FromForm] UserLayer entity)
    {
        using AppDbContext context = new();
        var transaction = context.Database.BeginTransaction();
        entity.CreatedTime = DateTime.Now;
        entity.UpdatedTime = DateTime.Now;
        entity.Count = 0;
        entity.CreatedUser = Thread.CurrentThread.Name;
        entity.UpdatedUser = Thread.CurrentThread.Name;

        try
        {
            context.UserLayers.Add(entity);
            context.SaveChanges();
            transaction.Commit();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            transaction.Rollback();
            throw;
        }

        return new JsonResult(new ResponseResult() { Data = entity.Id });
    }

    [HttpPut("{id}")]
    public IActionResult UpdateData(int id, [FromForm] UserLayer entity)
    {
        TryValidateModel(entity);
        using AppDbContext context = new();
        var transaction = context.Database.BeginTransaction();
        entity.UpdatedTime = DateTime.Now;
        try
        {
            entity.Id = id.ToString();
            context.UserLayers.Where(u => u.Id == id.ToString()).ExecuteUpdate(setter =>
                setter
                    .SetProperty(c => c.Name, entity.Name)
                    .SetProperty(c => c.ConditionText, entity.ConditionText)
                    .SetProperty(c => c.UpdatedTime, DateTime.Now)
                    .SetProperty(c => c.UpdatedUser, Thread.CurrentThread.Name)
            );
            context.SaveChanges();
            transaction.Commit();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            transaction.Rollback();
            throw;
        }

        return new JsonResult(1);
    }
}